import { useState, useEffect, useRef } from "react";
import { useParams, useNavigate } from "react-router-dom";
import * as echarts from "echarts";
import { ArrowLeft, Search, Calendar, Percent, AlertCircle } from "lucide-react";
import stockApi, { StockHistory, StockInfo, StockAnalysis, StockComparison } from "../services/stockApi";

// 获取股票名称的映射
const getStockName = (symbol: string): string => {
  const stockNames: { [key: string]: string } = {
    "000001": "平安银行",
    "000002": "万科A",
    "000858": "五粮液",
    "600000": "浦发银行",
    "600036": "招商银行",
    "600519": "贵州茅台",
    "600887": "伊利股份",
    "600588": "用友网络",
    "002415": "海康威视",
    "600276": "恒瑞医药",
    "000725": "京东方A",
    "002594": "比亚迪"
  };
  return stockNames[symbol] || `股票${symbol}`;
};

// 分析结果接口（与API返回的AnalysisData兼容）
interface AnalysisResult {
  id: string;
  period: string;
  similarity: number;
  start_price: number;
  end_price: number;
  change_percent: number;
}

// 转换API分析数据为本地格式
const convertAnalysisData = (analysisData: StockAnalysis): AnalysisResult[] => {
  return analysisData.results.map((result, index) => ({
    id: `analysis_${index}`,
    period: result.period,
    similarity: result.similarity,
    start_price: result.start_price,
    end_price: result.end_price,
    change_percent: result.change_percent
  }));
};

// 转换对比数据为图表格式
const convertComparisonData = (comparisonData: StockComparison) => {
  const currentData = comparisonData.current_period.data.map(item => [item.date, item.price]);
  const historicalData = comparisonData.historical_period.data.map(item => [item.date, item.price]);
  
  return { currentData, historicalData };
};

export default function Analysis() {
  const { stockCode } = useParams<{ stockCode: string }>();
  const navigate = useNavigate();
  const chartRef = useRef<HTMLDivElement>(null);
  const chartInstance = useRef<echarts.ECharts | null>(null);
  
  const [targetPeriod, setTargetPeriod] = useState(30);
  const [similarityThreshold, setSimilarityThreshold] = useState(70);
  const [analysisResults, setAnalysisResults] = useState<AnalysisResult[]>([]);
  const [selectedResult, setSelectedResult] = useState<AnalysisResult | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [stockInfo, setStockInfo] = useState<StockInfo | null>(null);
  const [apiHealthy, setApiHealthy] = useState<boolean | null>(null);
  const [comparisonData, setComparisonData] = useState<StockComparison | null>(null);

  // 检查API健康状态
  useEffect(() => {
    const checkApiHealth = async () => {
      try {
        const healthy = await stockApi.checkApiHealth();
        setApiHealthy(healthy);
      } catch (error) {
        setApiHealthy(false);
      }
    };
    
    checkApiHealth();
  }, []);

  // 获取股票基本信息
  useEffect(() => {
    const fetchStockInfo = async () => {
      if (!stockCode || !apiHealthy) return;
      
      try {
        const info = await stockApi.getStockInfo(stockCode);
        setStockInfo(info);
      } catch (error) {
        console.error('Failed to fetch stock info:', error);
        // 股票信息获取失败不影响分析功能
      }
    };
    
    fetchStockInfo();
  }, [stockCode, apiHealthy]);

  // 初始化图表
  useEffect(() => {
    const initChart = () => {
      if (!chartRef.current) {
        console.log('Chart container not available yet');
        return;
      }

      if (chartInstance.current) {
        console.log('Chart already initialized');
        return;
      }

      try {
        const container = chartRef.current;
        console.log('Initializing chart, container dimensions:', {
          width: container.offsetWidth,
          height: container.offsetHeight,
          display: window.getComputedStyle(container).display,
          visibility: window.getComputedStyle(container).visibility
        });

        // 确保容器有正确的尺寸
        if (container.offsetWidth === 0 || container.offsetHeight === 0) {
          console.warn('Container has zero dimensions, forcing size');
          container.style.width = '100%';
          container.style.height = '400px';
          container.style.minHeight = '400px';
          
          // 等待一帧后重试
          requestAnimationFrame(() => {
            if (container.offsetWidth > 0 && container.offsetHeight > 0) {
              initChart();
            }
          });
          return;
        }

        // 初始化ECharts实例
        chartInstance.current = echarts.init(container);
        console.log('Chart initialized successfully, instance:', !!chartInstance.current);

        // 设置默认选项
        const defaultOption = {
          title: {
            text: '图表已准备就绪',
            left: 'center',
            top: 'center',
            textStyle: {
              color: '#999',
              fontSize: 16
            }
          },
          backgroundColor: '#fafafa'
        };
        chartInstance.current.setOption(defaultOption);
        console.log('Default chart option set');

      } catch (error) {
        console.error('Failed to initialize chart:', error);
      }
    };

    // 多次尝试初始化以确保成功
    const timer1 = setTimeout(initChart, 50);
    const timer2 = setTimeout(initChart, 200);
    const timer3 = setTimeout(initChart, 500);

    const handleResize = () => {
      if (chartInstance.current) {
        console.log('Resizing chart');
        chartInstance.current.resize();
      }
    };
    window.addEventListener('resize', handleResize);

    return () => {
      clearTimeout(timer1);
      clearTimeout(timer2);
      clearTimeout(timer3);
      window.removeEventListener('resize', handleResize);
      if (chartInstance.current) {
        console.log('Disposing chart instance');
        chartInstance.current.dispose();
        chartInstance.current = null;
      }
    };
  }, []);

  // 更新对比图表
  useEffect(() => {
    const updateChart = () => {
      console.log('updateChart called, chartInstance:', !!chartInstance.current, 'selectedResult:', !!selectedResult);
      
      if (!chartInstance.current) {
        console.log('Chart instance not available, waiting...');
        return;
      }

      if (!selectedResult) {
        console.log('No selectedResult, showing placeholder');
        // 显示占位符
        const placeholderOption = {
          title: {
            text: '请选择分析结果查看对比图表',
            left: 'center',
            top: 'center',
            textStyle: {
              color: '#999',
              fontSize: 16
            }
          },
          backgroundColor: '#fafafa'
        };
        chartInstance.current.setOption(placeholderOption, true);
        return;
      }

      try {
        console.log('Using comparison data for selectedResult:', selectedResult.id);
        
        if (!comparisonData) {
          console.log('No comparison data available');
          const noDataOption = {
            title: {
              text: '暂无对比数据',
              left: 'center',
              top: 'center',
              textStyle: {
                color: '#999',
                fontSize: 16
              }
            }
          };
          chartInstance.current.setOption(noDataOption, true);
          return;
        }
        
        const { currentData, historicalData } = convertComparisonData(comparisonData);
        
        console.log('Chart data converted:', { 
          currentDataLength: currentData.length, 
          historicalDataLength: historicalData.length,
          selectedResultId: selectedResult.id,
          targetPeriod: targetPeriod,
          firstCurrentDate: currentData[0]?.[0],
          lastCurrentDate: currentData[currentData.length - 1]?.[0]
        });
        
        if (currentData.length === 0 || historicalData.length === 0) {
          console.warn('No data available for chart');
          const noDataOption = {
            title: {
              text: '暂无数据',
              left: 'center',
              top: 'center',
              textStyle: {
                color: '#999',
                fontSize: 16
              }
            }
          };
          chartInstance.current.setOption(noDataOption, true);
          return;
        }

        const option = {
          backgroundColor: '#ffffff',
          title: {
            text: `${stockCode} ${getStockName(stockCode || '')} - 走势对比 - 相似度: ${selectedResult.similarity}%`,
            left: 'center',
            top: 10,
            textStyle: {
              fontSize: 16,
              fontWeight: 'bold',
              color: '#333'
            }
          },
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'cross'
            },
            formatter: function(params: any) {
              let result = params[0].axisValue + '<br/>';
              params.forEach((param: any) => {
                result += `${param.seriesName}: ${param.value}<br/>`;
              });
              return result;
            }
          },
          legend: {
            data: ['当前走势', '历史走势'],
            top: 35,
            textStyle: {
              color: '#666'
            }
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '8%',
            top: '15%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: currentData.map(item => item[0]),
            boundaryGap: false,
            axisLabel: {
              color: '#666',
              rotate: 45,
              fontSize: 10
            }
          },
          yAxis: {
            type: 'value',
            scale: true,
            axisLabel: {
              color: '#666'
            }
          },
          series: [
            {
              name: '当前走势',
              type: 'line',
              data: currentData.map(item => item[1]),
              lineStyle: {
                color: '#3b82f6',
                width: 2
              },
              symbol: 'circle',
              symbolSize: 4,
              smooth: true
            },
            {
              name: '历史走势',
              type: 'line',
              data: historicalData.map(item => item[1]),
              lineStyle: {
                color: '#ef4444',
                width: 2,
                type: 'dashed'
              },
              symbol: 'circle',
              symbolSize: 4,
              smooth: true
            }
          ]
        };
        
        console.log('Setting chart option...');
        chartInstance.current.setOption(option, true);
        
        // 确保图表正确渲染
        setTimeout(() => {
          if (chartInstance.current) {
            console.log('Resizing chart after option update');
            chartInstance.current.resize();
          }
        }, 100);
        
        console.log('Chart updated successfully with new data');
      } catch (error) {
        console.error('Failed to update chart:', error);
      }
    };

    // 多次尝试更新以确保成功
    const timer1 = setTimeout(updateChart, 50);
    const timer2 = setTimeout(updateChart, 200);
    const timer3 = setTimeout(updateChart, 500);

    return () => {
      clearTimeout(timer1);
      clearTimeout(timer2);
      clearTimeout(timer3);
    };
  }, [selectedResult, targetPeriod]);

  const handleAnalysis = async () => {
    if (!stockCode) return;
    
    setLoading(true);
    setError(null);
    console.log('开始分析，参数:', { targetPeriod, similarityThreshold });
    
    try {
      // 检查API是否可用
      if (apiHealthy === false) {
        throw new Error('股票数据API服务不可用，请确保后端服务已启动');
      }
      
      // 如果API健康但还未完成检查，等待一下
      if (apiHealthy === null) {
        throw new Error('正在连接股票数据服务...');
      }
      
      // 调用分析API
      const analysisData = await stockApi.getStockAnalysis(stockCode, targetPeriod);
      const results = convertAnalysisData(analysisData);
      
      console.log('分析完成，结果数量:', results.length);
      setAnalysisResults(results);
      
      // 自动选择第一个结果并获取对比数据
      if (results.length > 0) {
        console.log('自动选择第一个结果:', results[0]);
        setSelectedResult(results[0]);
        
        // 获取对比数据
        try {
          const comparison = await stockApi.getStockComparison(
             stockCode, 
             results[0].period, 
             targetPeriod
           );
          setComparisonData(comparison);
        } catch (compError) {
          console.error('Failed to fetch comparison data:', compError);
          // 对比数据获取失败不影响分析结果显示
        }
      } else {
        console.warn('没有分析结果');
        setComparisonData(null);
      }
    } catch (error) {
      console.error('Analysis failed:', error);
      setError(error instanceof Error ? error.message : '分析失败');
      setAnalysisResults([]);
      setSelectedResult(null);
      setComparisonData(null);
    } finally {
      setLoading(false);
    }
  };

  // 处理选择分析结果
  const handleSelectResult = async (result: AnalysisResult) => {
    console.log('选择分析结果:', result);
    setSelectedResult(result);
    
    if (!stockCode) return;
    
    try {
      // 获取对应的对比数据
      const comparison = await stockApi.getStockComparison(
         stockCode, 
         result.period, 
         targetPeriod
       );
      setComparisonData(comparison);
    } catch (error) {
      console.error('Failed to fetch comparison data for selected result:', error);
      // 对比数据获取失败时清空数据
      setComparisonData(null);
    }
  };

  const getHighlightedResults = () => {
    return analysisResults.filter(result => result.similarity >= similarityThreshold);
  };

  const getSimilarityColor = (similarity: number) => {
    if (similarity >= 80) return 'text-green-600 bg-green-50';
    if (similarity >= 60) return 'text-yellow-600 bg-yellow-50';
    return 'text-red-600 bg-red-50';
  };

  return (
    <div className="min-h-screen bg-gray-50 p-4">
      <div className="max-w-7xl mx-auto">
        {/* 头部导航 */}
        <div className="bg-white rounded-lg shadow-sm p-4 mb-4">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-4">
              <button
                onClick={() => navigate(`/chart/${stockCode}`)}
                className="flex items-center gap-2 text-gray-600 hover:text-gray-800 transition-colors"
              >
                <ArrowLeft size={20} />
                返回图表
              </button>
              <div className="h-6 w-px bg-gray-300"></div>
              <h1 className="text-xl font-semibold text-gray-800">
                历史对比分析 - {stockCode} {stockInfo?.name || getStockName(stockCode || '')}
              </h1>
              {stockInfo && (
                <div className="text-sm text-gray-600">
                  {stockInfo.name} ({stockInfo.symbol})
                </div>
              )}
            </div>
            {apiHealthy === false && (
              <div className="flex items-center space-x-2 text-red-600">
                <AlertCircle className="h-4 w-4" />
                <span className="text-sm">API服务不可用</span>
              </div>
            )}
          </div>
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-3 gap-4">
          {/* 分析参数设置 */}
          <div className="lg:col-span-1">
            <div className="bg-white rounded-lg shadow-sm p-4 mb-4">
              <h2 className="text-lg font-semibold text-gray-800 mb-4">分析参数</h2>
              
              <div className="space-y-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    <Calendar size={16} className="inline mr-1" />
                    分析期间（天）
                  </label>
                  <input
                    type="number"
                    value={targetPeriod}
                    onChange={(e) => setTargetPeriod(Number(e.target.value))}
                    min="7"
                    max="365"
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                  />
                </div>
                
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    <Percent size={16} className="inline mr-1" />
                    相似度阈值（%）
                  </label>
                  <input
                    type="number"
                    value={similarityThreshold}
                    onChange={(e) => setSimilarityThreshold(Number(e.target.value))}
                    min="0"
                    max="100"
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                  />
                </div>
                
                <button
                  onClick={handleAnalysis}
                  disabled={loading || apiHealthy === false}
                  className="w-full bg-blue-600 hover:bg-blue-700 disabled:bg-gray-400 text-white font-medium py-2 px-4 rounded-lg transition-colors flex items-center justify-center gap-2"
                >
                  {loading ? (
                    <>
                      <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white"></div>
                      分析中...
                    </>
                  ) : (
                    <>
                      <Search size={16} />
                      开始分析
                    </>
                  )}
                </button>
              </div>
            </div>

            {/* 分析结果列表 */}
            {analysisResults.length > 0 && (
              <div className="bg-white rounded-lg shadow-sm p-4">
                <div className="flex items-center justify-between mb-4">
                  <h3 className="text-lg font-semibold text-gray-800">分析结果</h3>
                  <span className="text-sm text-gray-600">
                    {getHighlightedResults().length} / {analysisResults.length} 个高相似度
                  </span>
                </div>
                
                <div className="space-y-2 max-h-96 overflow-y-auto">
                  {analysisResults.map((result) => (
                    <div
                      key={result.id}
                      onClick={() => handleSelectResult(result)}
                      className={`p-3 rounded-lg border cursor-pointer transition-all ${
                        selectedResult?.id === result.id
                          ? 'border-blue-500 bg-blue-50'
                          : 'border-gray-200 hover:border-gray-300 hover:bg-gray-50'
                      } ${
                        result.similarity >= similarityThreshold
                          ? 'ring-2 ring-yellow-200'
                          : ''
                      }`}
                    >
                      <div className="flex items-center justify-between mb-2">
                        <span className="font-medium text-gray-800">{result.period}</span>
                        {result.similarity >= similarityThreshold && (
                          <AlertCircle size={16} className="text-yellow-600" />
                        )}
                      </div>
                      <div className="text-sm text-gray-600 mb-2">
                        价格变化: {result.start_price} → {result.end_price} ({result.change_percent.toFixed(2)}%)
                      </div>
                      <div className={`inline-flex items-center px-2 py-1 rounded text-sm font-medium ${
                        getSimilarityColor(result.similarity)
                      }`}>
                        相似度: {result.similarity}%
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            )}
          </div>

          {/* 对比图表 */}
          <div className="lg:col-span-2">
            <div className="bg-white rounded-lg shadow-sm p-4">
              <div className="mb-4">
                <h3 className="text-lg font-semibold text-gray-800 mb-2">
                  走势对比分析
                </h3>
                {selectedResult && (
                  <div className="text-sm text-gray-600">
                    对比期间: {selectedResult.period} (相似度: {selectedResult.similarity}%)
                  </div>
                )}
              </div>
              
              {/* 图表容器区域 */}
              <div className="relative">
                {/* 图表容器始终存在 */}
                <div
                  ref={chartRef}
                  className="w-full h-96 bg-white"
                  style={{ 
                    minHeight: '400px',
                    height: '400px',
                    width: '100%',
                    display: 'block',
                    position: 'relative'
                  }}
                />
                
                {/* 错误显示覆盖层 */}
                {error && (
                  <div className="absolute inset-0 flex items-center justify-center bg-white bg-opacity-90 rounded-lg z-10">
                    <div className="text-center">
                      <AlertCircle size={48} className="text-red-500 mx-auto mb-4" />
                      <p className="text-red-600 mb-4">{error}</p>
                      <button
                        onClick={() => setError(null)}
                        className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 transition-colors"
                      >
                        关闭
                      </button>
                    </div>
                  </div>
                )}
                
                {/* 无数据时的覆盖层 */}
                {!error && !selectedResult && (
                  <div className="absolute inset-0 flex items-center justify-center bg-white bg-opacity-90 rounded-lg">
                    <div className="text-center text-gray-500">
                      <Search size={48} className="mx-auto mb-4 opacity-50" />
                      <p>请先设置参数并开始分析</p>
                    </div>
                  </div>
                )}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}